package com.gurid.service.trade.controller.api;

import com.github.wxpay.sdk.WXPayUtil;
import com.gurid.common.base.result.R;
import com.gurid.service.trade.entity.Order;
import com.gurid.service.trade.service.OrderService;
import com.gurid.service.trade.service.WeixinPayService;
import com.gurid.service.trade.util.StreamUtils;
import com.gurid.service.trade.util.WeixinPayProperties;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/trade/weixin-pay")
@Tag(name = "ApiWeixinPayController", description = "网站微信支付")
//@CrossOrigin
@Slf4j
public class ApiWeixinPayController {
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private WeixinPayProperties weixinPayProperties;
    @Autowired
    private OrderService orderService;

    @GetMapping("create-native/{orderNo}")
    public R createNative(@PathVariable String orderNo, HttpServletRequest request) {

        String remoteAddr = request.getRemoteAddr();
        System.out.println("orderNo:" + orderNo);
        Map<String, Object> map = weixinPayService.createNative(orderNo, remoteAddr);
        return R.ok().data(map);
    }

    @PostMapping("callback/notify")
    public String wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {

        ServletInputStream inputStream = request.getInputStream();
        String notifyXml = StreamUtils.inputStream2String(inputStream, "utf-8");
        log.info("notify xml:{}", notifyXml);
        //验证签名
        if (WXPayUtil.isSignatureValid(notifyXml, weixinPayProperties.getPartnerKey())) {
            Map<String, String> map = WXPayUtil.xmlToMap(notifyXml);
            //判断支付是否成功
            if ("SUCCESS".equals(map.get("result_code"))) {
                //金额校验
                String totalFee = map.get("total_fee");
                String outTradeNo = map.get("out_trade_no");
                Order order = orderService.getOrderByOrderNo(outTradeNo);
                //对比金额是否一致
                if (order != null && order.getTotalFee().intValue() == Integer.parseInt(totalFee)) {
                    //接口调用的幂等性：无论调用多少次，最后所影响的结果都是一致的
                    //就是阻止订单重复执行
                    if (order.getStatus() == 0) {
                        //更新订单状态
                        orderService.updateOrderStatus(map);
                    } else {
                        //支付成功，发送响应
                        Map<String, String> returnMap = new HashMap<>();
                        returnMap.put("return_code", "SUCCESS");
                        returnMap.put("return_msg", "OK");
                        String resultXml = WXPayUtil.mapToXml(returnMap);
                        response.setContentType("text/xml;charset=utf-8");
                        log.info("已经接收到通知");

                        return resultXml;
                    }


                }
            }
        }
        //支付失败，微信接收到失败的响应后会反复发送
        Map<String, String> returnMap = new HashMap<>();
        returnMap.put("return_code", "FAIL");
        returnMap.put("return_msg", "");
        String resultXml = WXPayUtil.mapToXml(returnMap);
        response.setContentType("text/xml;charset=utf-8");
        log.info("校验失败");

        return resultXml;
    }
}
